<template>
  <div class="modify-student">
    <header class="modify-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left"/>返回</span>
        <span>|</span>
        <span>学生信息修改</span>
      </div>
      <div class="right">
        课程管理系统
      </div>
    </header>
    <main class="modify-main">
      <div class="form-container" style="line-height: 100px;text-align:center;">
        <!--头像上传-->
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8081/file/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>

        <!-- 学生信息 -->
        <el-form ref="form" :model="form" :rules="rules">
          <el-form-item label="学生姓名" prop="studentName">
            <el-input v-model="form.studentName"/>
          </el-form-item>
          <el-form-item label="学生班级" prop="className">
            <el-input v-model="form.className"/>
          </el-form-item>
          <el-form-item label="学号" prop="studentNumber">
            <el-input v-model="form.studentNumber"/>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" type="email"/>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="form.password" show-password :disabled="!modifyPw"/>
          </el-form-item>
        </el-form>
        <el-checkbox v-model="modifyPw" @change="resetPW">修改密码</el-checkbox>
      </div>
    </main>
    <footer class="modify-footer">
      <div class="btn-container">
        <el-button @click="reset()">重置</el-button>
        <el-button type="primary" @click="modifyInfo">确认修改</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import {getInfoAPI_Student, modifyAPI_Student} from "@/api/student/personal";
import {
  getUserIDLocalStorage,
  updateUserInfoLocalStorage
} from "@/utils/utilLocalStorage";
import {isEmpty} from "@/utils/checkString";
import eventBus from "@/main";
import {DATA_OK_NUM} from "@/constants/KEY";

export default {
  data() {
    //自定义的邮箱和手机验证规则
    let checkEmail = (rule, value, callback) => {//验证邮箱
      const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (this.form.email !== '' && !regEmail.test(this.form.email)) {
        callback(new Error('请输入有效的邮箱'));
      }
    };
    return {
      imageUrl: '',
      modifyPw: false, //是否修改密码
      form: {
        avatar: '',
        studentName: '',
        className: '',
        studentNumber: '',
        email: '',
        password: null,
      },
      // 输入规则
      rules: {
        studentName: [
          {required: true, message: '学生姓名必须填写，如：张三', trigger: 'blur'},
          {min: 1, max: 18, required: true, message: '姓名必须1-18位', trigger: 'blur'}
        ],
        studentNumber: [
          {required: true, message: '学号必须填写，如：0000001', trigger: 'blur'},
          {min: 3, max: 16, required: true, message: '学号必须3-16位', trigger: 'blur'},
          // { type: 'number', message: '教职工号必须为数字值' }
        ],
        email: [
          {required: true, message: '请输入邮箱，如：8888888@qq.com', trigger: 'blur'},
          {validator: checkEmail, trigger: "blur"}],
        password: [
          {required: true, message: '密码必须填写', trigger: 'blur'},
          {min: 3, max: 16, required: true, message: '密码必须3-16位', trigger: 'blur'},
        ],
      },
    }
  },
  mounted() {
    this.getInfo()
  },
  methods: {
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      this.imageUrl = res.data;
      this.form.avatar = res.data
      // console.log('resUP: ',res)
      // console.log('fileUP: ',file)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 10;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG或PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 10MB!');
      }
      return isJPG && isLt2M;
    },
    // 重置方法
    reset() {
      this.form.avatar = ''
      this.form.studentName = ''
      this.form.className = ''
      this.form.studentNumber = ''
      this.form.email = ''
      this.form.password = null
    },
    resetPW(value) {
      // 如果不修改密码单选框，则将form.pw = null
      if (!value) {
        this.form.password = null
      }
    },
    getInfo() {
      getInfoAPI_Student(getUserIDLocalStorage()).then((res) => {
        // console.log('获取信息返回：', res)
        this.form = {
          // avatar: res.data.avatar || '',
          avatar: null,
          studentName: res.data.studentName || '',
          className: res.data.className || '',
          studentNumber: res.data.studentNumber || '',
          email: res.data.email || '',
          // password: res.data.password || null,
          password: null,
        };
      })
    },
    modifyInfo() {
      if(isEmpty(this.form.password) && this.modifyPw){
        this.$message.error('修改密码时，必须填写密码或密码不符合规范！')
        return
      }
      // 二次确认是否修改信息
      this.$confirm('确认修改个人信息?').then(async() => {
        modifyAPI_Student(this.form).then((res) => {
          // console.log('修改信息返回：', res)
          if (res.data === DATA_OK_NUM) {
            this.$message.success('修改成功！')
            // 修改本地存储的头像路径
            this.form.password = '***'
            this.form.id = getUserIDLocalStorage()
            updateUserInfoLocalStorage(this.form)
            window.location.reload();
            // 在页面刷新后跳转到特定页面
            window.location.href = '/student/information';

          } else {
            this.$message.error('修改失败！')
          }
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
.modify-student {
  background-color: #f4f6f8;
  height: 100vh;

  .modify-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .modify-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;
      padding-left: 300px;
      padding-right: 300px;
      padding-bottom: 100px;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .modify-footer {
    position: fixed;
    bottom: 10px;
    width: 100%;
    padding: 30px 50px;
    color: #000000d9;
    font-size: 18px;
    background: #fff;
    text-align: center;
  }

  // 头像上传
  .avatar-uploader .el-upload {
    border: 1px dashed #bd2525;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #4770a9;
    width: 136px;
    height: 136px;
    line-height: 136px;
    text-align: center;
  }

  .avatar {
    width: 136px;
    height: 136px;
    display: block;
  }
}
</style>
